const DB = require('../../../utils/db')
// 引入jwt token工具
const JwtUtil = require('../../../utils/jwt')
/**
 * GET
 * 获取动态列表
 */
module.exports = async (ctx) => {
  let label = ctx.request.query.label
  // 是否只查看我自己的
  let isme = ctx.request.query.isme
  let res
  // 获取token
  
  let token = ctx.request.header.authorization

  let jwt = new JwtUtil(token)
  // 用token获取到userid
  let userid = jwt.verifyToken()
  // 全部
  if (parseInt(label) === 0 || isNaN(label)) {
    let sql = `select userid, createTime, updateTime, label, textContent, imgUrl, title, id, commentTotal,heartId from  dynamic `
    if(isme){
      console.log(89);
      sql += `where userid = '${userid}' `
    }
    sql += ` order by updateTime desc`
    res = await DB.query(
      sql
    )
    console.log(res)
  } else {
         console.log(819)
    let sql = `select userid, createTime, updateTime, label, textContent, imgUrl, title, id , commentTotal,heartId from  dynamic where label='${label}' `
    sql += ` order by updateTime desc`
    res = await DB.query(
      sql
    )
  }

  res.forEach(function (item, index) {
    let heartId = item.heartId
    // true表示点赞， false表示没有点赞
    let isHeart = false
    if (heartId !== null) {
      heartId.split(',').forEach(function (item, index) {
        // console.log(item,9999);
        if (item === userid) {
          isHeart = true
        }
      })
    }
    // console.log(isHeart,res, 100909)
    item.isHeart = isHeart
  })  
  // console.log(res,'res')
  ctx.body = {
    code: 0,
    data: res,
  }
}
